<?php

// FUNZIONI DI TEMPLATING
function getSkinPath() {
    return "skins/shifter/dtml/";
}

function setSectionContent($section, $content, $skinPage) {
    $code = new Template(getSkinPath() . $skinPage . ".html");
    $section->setContent($content, $code->get());
}

function setSectionContentString($section, $content, $string) {
    $section->setContent($content, $string);
}

function setSectionContentImage($section, $content, $imageURL) {
    $section->setContent($content, 'uploads/' . $imageURL);
}

function setButton($text = 'Submit', $link = '', $alert = false) {
    $btn = setBody('components/button');
    setSectionContentString($btn, 'button_text', $text);
    setSectionContentString($btn, 'button_link', $link);
    if ($alert)
        setSectionContentString($btn, 'button_more', 'onclick="return confirm(\'Sicuro?\');"');

    return $btn;
}

// FUNZIONI DI GESTIONE
function getMWTcrypt($string) {
    return md5(md5($string));
}

function sendEmail($msg, $dest, $obj) {
    mail($dest, $obj, $msg);
}

function time_elapsed($secs) {
    $secs = time() - $secs;
    $bit = array(
        ' year' => $secs / 31556926 % 12,
        ' week' => $secs / 604800 % 52,
        ' day' => $secs / 86400 % 7,
        ' hour' => $secs / 3600 % 24,
        ' minute' => $secs / 60 % 60,
        ' second' => $secs % 60
    );

    foreach ($bit as $k => $v) {
        if ($v > 1)
            $ret[] = $v . $k . 's';
        if ($v == 1)
            $ret[] = $v . $k;
    }
    array_splice($ret, count($ret) - 1, 0, 'and');
    $ret[] = 'ago.';

    return join(' ', $ret);
}

/**
 * This method does a redirection to a page PHP
 * @param type $page Page PHP to redirect
 */
function redirect($page = "index") {
    Header("Location: " . $page . ".php");
    exit;
}

function redirectS($url) {
    Header("location: " . $url);
    exit;
}

/**
 * This method does a redirection to a page PHP using post method 
 * @param type $page Page PHP to redirect
 * @param type $cond Associative array who defines Request  
 */
function redirectPost($page, $cond) {
    $query = "";
    foreach ($cond as $key => $value) {
        $query = $query . $key . "=" . $value . "&";
    }
    $query = rtrim($query, "&");
    Header("Location: " . $page . ".php?" . $query);
    exit;
}

// CONTROLLI E FUNZIONI SUGLI UTENTI
function userIsLoggedIn() {
    //return ($user != null);
    //return ($GLOBALS['user_obj'] != null);
    if (isset($_SESSION['login'])) {
        return $_SESSION['login'];
    } else {
        return false;
    }
}

//MODIFICARE CON METODI DI CLASSE!!!!!!!!!!!!!
function isUserOnGroup($group) {
    if (userIsLoggedIn()) {
        $user = unserialize($_SESSION['user']);
        return ($user->getGroup() === $group);
    }
    return false;
}

function isAdmin() {
    return isUserOnGroup("Admin");
}

function isProf() {
    return isUserOnGroup("Professors");
}

function isStud() {
    return isUserOnGroup("Students");
}

function getIDbyUsername($mysqli, $username) {
    $sql = 'SELECT id FROM users WHERE username = \'' . $username . '\'';
    if ($data = $mysqli->query($sql)) {
        if (mysqli_num_rows($data)) {
            //SE E' STATO TROVATO UN UTENTE CON QUESTA USERNAME
            $row = $data->fetch_array(MYSQLI_ASSOC);
            return $row['id'];
        }
    }
}

function getGroups($mysqli) {
    $sql = "SELECT * FROM groups";
    if ($data = $mysqli->query($sql)) {
        return $data;
    } else
        displayDBError($mysqli, $body);
    return null;
}

function setSectionContentTeacher($teachers, $body, $idTeachers) {
    foreach ($teachers as $key => $row) {
        $body->setContent("teacherid", $row['id']);
        $teachername = $row['first_name'] . " " . $row['last_name'];
        $body->setContent("teachername", $teachername);
        if (($idTeachers != NULL) && ($idTeachers == $row['id'])) {
            $body->setContent("teacherselected", "selected");
        }
    }
}

function setSectionContentCourse($courses, $body, $idCourse) {
    foreach ($courses as $key => $row) {
        $body->setContent("courseid", $row['id']);
        $body->setContent("coursename", $row['name']);
        if (($idCourse != NULL) && ($idCourse == $row['id'])) {
            $body->setContent("courseselected", "selected");
        }
    }
}

function setSectionContentCoursebyName($courses, $body, $nameCourse) {
    foreach ($courses as $key => $row) {
        $body->setContent("courseid", $row['id']);
        $body->setContent("coursename", $row['name']);
        if (($nameCourse != NULL) && ($nameCourse == $row['name'])) {
            $body->setContent("courseselected", "selected");
        }
    }
}

function displayDBError($mysqli, $body) {
    $body->setContent("errormessage", $mysqli->errno . " - " . $mysqli->error);
}

function queryInsert($table, $arr) {
    $start = "INSERT INTO " . $table;
    $keys = " (";
    $values = " VALUES (";
    foreach ($arr as $key => $value) {
        $keys = $keys . '`' . $key . '`,';
        $values = $values . "'" . $value . "',";
    }
    $keys = rtrim($keys, ",") . ')';
    $values = rtrim($values, ",") . ')';
    return $start . $keys . $values;
}

function queryUpdateEasy($table, $arr, $cond) {
    $query = "UPDATE " . $table . " SET ";
    foreach ($arr as $key => $value) {
        $query = " " . $query . $key . " = '" . $value . "', ";
    }
    $query = rtrim($query, ", ") . " WHERE ";
    foreach ($cond as $key => $value) {
        $query = $query . " " . $key . "= '" . $value . "' AND";
    }
    $query = rtrim($query, "AND");
    return $query;
}

function queryDeleteEasy($table, $cond) {
    $query = "DELETE FROM " . $table;
    $query = $query . " WHERE ";
    foreach ($cond as $key => $value) {
        $query = $query . " " . $key . "= '" . $value . "' AND";
    }
    $query = rtrim($query, "AND");
    return $query;
}

function querySelectEasy($table, $arr = '*', $cond = '') {
    $query = "SELECT ";
    foreach ($arr as $key => $value) {
        $query = $query . $key . ", ";
    }
    $query = rtrim($query, ", ") . " FROM " . $table . " WHERE ";
    foreach ($cond as $key => $value) {
        $query = " " . $query . $key . "= '" . $value . "' AND";
    }
    $query = rtrim($query, "AND");
    return $query;
}

function getData($data) {
    $ora = substr($data, 10);
    $giorno = substr($data, 8, 2);
    $mese = substr($data, 5, 2);
    $anno = substr($data, 0, 4);
    return $giorno . "/" . $mese . "/" . $anno;
}

function getLanguage() {
    $language = "";
    //$lang = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
    $lang = "it";
    if (isset($_GET) && isset($_GET['lang']) && $_GET['lang'] == 'en') {
        $lang = "en";
    }
    switch ($lang) {
        case "it":
            $language = "it";
            break;
        default:
            $language = "en";
            break;
    }
    return $language;
}
